package com.sunny.l78;

import java.util.Iterator;
import java.util.Stack;

/**
 *  Given an absolute path for a file (Unix-style), simplify it.

 For example,
 path ="/home/", =>"/home"
 path ="/a/./b/../../c/", =>"/c"

 click to show corner cases.
 */
public class Solution {
    public String simplifyPath(String path) {
        Stack<String> stack = new Stack<>();
        String[] paths = path.split("/");
        for(int i=0;i<paths.length;i++){
            if(".".equals(paths[i]) || "".equals(paths[i]))
                continue;
            if("..".equals(paths[i])){
                if(!stack.isEmpty())
                    stack.pop();
            }else{
                stack.push(paths[i]);
            }
        }
        if(stack.isEmpty()){
            return "/";
        }
        StringBuilder sb = new StringBuilder();
        Iterator<String> iter = stack.iterator();
        while (iter.hasNext()){
            sb.append("/").append(iter.next());
        }
        return sb.toString();
    }
}